<script setup lang="ts">
import { useRouter } from 'vue-router'
import { DeleteOutlined, DollarOutlined } from '@ant-design/icons-vue'
import { delCartUsingDelete, purchaseProductByCartUsingPost } from '@/api/cartController.ts'
import { message } from 'ant-design-vue'

const router = useRouter()

interface Props {
  dataList?: API.ProductVo[]
  loading?: boolean
  showOp?: boolean
  onReload?: () => void
}

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  onReload: () => {},
})

// 跳转到商品详情页
const doProductClick = (item: any) => {
  if (item.productId) {
    router.push({
      path: `/product/detail/${item.productId}`,
    })
  } else {
    router.push({
      path: `/product/detail/${item.id}`,
    })
  }
}

// 购买
const doPurchase = async (cart: API.CartVo, e: any) => {
  // 阻止事件冒泡
  e.stopPropagation()
  const cartId = cart.cartId
  if (!cartId) {
    return
  }
  const res = await purchaseProductByCartUsingPost({
    cartId,
  })
  if (res.code === 200) {
    message.success('购买成功')
    props.onReload?.()
  } else {
    message.error(res.message)
  }
}

// 删除
const doDelete = async (cart: API.CartVo, e: any) => {
  // 阻止事件冒泡
  e.stopPropagation()
  const cartId = cart.cartId
  if (!cartId) {
    return
  }
  const res = await delCartUsingDelete({
    cartId,
  })
  if (res.code === 200) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error(res.message)
  }
}
</script>

<template>
  <div class="image-list">
    <!-- 图片列表 -->
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item }">
        <a-list-item style="padding: 0">
          <!-- 单张图片 -->
          <a-card hoverable @click="doProductClick(item)">
            <template #cover>
              <a-image placeholder :src="item.image" height="180px" />
            </template>
            <a-card-meta :title="item.name" :description="item.description" />
            <template v-if="showOp" #actions>
              <a-tooltip color="green">
                <template #title>购买</template>
                <DollarOutlined key="purchase" @click="(e: any) => doPurchase(item, e)" />
              </a-tooltip>
              <a-tooltip color="red">
                <template #title>删除</template>
                <DeleteOutlined key="delete" @click="(e: any) => doDelete(item, e)" />
              </a-tooltip>
            </template>
          </a-card>
        </a-list-item>
      </template>
    </a-list>
  </div>
</template>

<style scoped></style>
